package com.tensai.core.mvc.system.controller;

import com.alibaba.fastjson.JSON;
import com.tensai.core.mvc.base.controller.BaseController;
import com.tensai.core.mvc.base.tools.ResultJson;
import com.tensai.core.mvc.base.tools.XTree;
import com.tensai.core.constant.ResponseStatus;
import com.tensai.core.mvc.system.entry.SysGroup;
import com.tensai.core.mvc.system.entry.SysMenu;
import com.tensai.core.mvc.system.facade.UserMenu;
import com.tensai.core.mvc.system.service.ISysGroupService;
import com.tensai.core.mvc.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 用菜单控制器
 *
 * @author Tensai
 * 2018/12/29
 */
@Controller
@RequestMapping("/system/menu/")
public class SysMenuController extends BaseController<SysMenu, Integer, ISysMenuService> {

    @Autowired
    private ISysMenuService sysMenuService;

    @Autowired
    private ISysGroupService sysGroupService;

    /**
     * 保存实体
     *
     * @param sysMenu   资源实体
     * @return          操作结果
     */
    @RequestMapping("/save")
    @ResponseBody
    @Override
    public ResultJson save(SysMenu sysMenu) {
        if (sysMenu.getParent() == null) {
            sysMenu.setLevel(1);
        } else {
            sysMenu.setLevel(sysMenu.getParent().getLevel() + 1);
        }
        return getService().save(sysMenu);
    }

    /**
     * 获取页面左侧菜单
     * @return  菜单列表
     */
    @RequestMapping("/getMenus")
    @ResponseBody
    public ResultJson getMenus(){
        List<UserMenu> menus = getService().getUserMenus();
        return new ResultJson(ResponseStatus.QUERY_SUCCESS, menus);
    }

    @RequestMapping("/findByType")
    @ResponseBody
    public ResultJson findByType(String type) {
        return new ResultJson(ResponseStatus.QUERY_SUCCESS, getService().findByType(type));
    }

    /**
     * 获取用户对于菜单的权限
     * @param id    用户组id
     * @return      菜单权限列表
     */
    @RequestMapping("/getMenusAuth")
    @ResponseBody
    public List<XTree> getMenus(Integer id){
        SysGroup sysGroup = sysGroupService.findOne(id);
        //JSON的权限判断
        List<Integer> list = JSON.parseArray(sysGroup.getMenuJson(), Integer.class);
        return getService().getUserMenus(list);
    }

    @Override
    protected void initEntity() {
        this.entity = new SysMenu();
    }
}

